/*
 * UI.c
 *
 *  Created on: Jul 1, 2024
 *      Author: W
 */

#include "UI.h"
#include "../LVGL/lvgl.h"
#include <stdio.h>
#include "../Images/images.h"

/* 定义UI对象 - 确保全局指针初始化为NULL */
lv_obj_t *background_img = NULL;
lv_obj_t *prop_img = NULL;
lv_obj_t *character_img = NULL;
lv_obj_t *fps_label = NULL;
static lv_timer_t *animation_timer = NULL; // 保存定时器引用以便正确管理

// 动画状态变量
static uint8_t movement_phase = 0;  // 当前移动阶段：0=中间到左边, 1=左边到右边, 2=右边到中间
static uint8_t frame_index = 0;     // 当前帧索引
static uint32_t last_flip_time = 0; // 上次道具翻转时间
static uint32_t last_frame_time = 0; // 上次帧更新时间
static uint32_t frame_start_time = 0; // 当前帧开始时间，用于计算帧内进度

// 性能监控相关变量
static uint32_t frame_count = 0;    // 帧率计数
static uint32_t last_fps_update = 0; // 上次帧率更新时间
static uint32_t fps_values[10] = {0}; // 存储最近10次FPS值
static uint8_t fps_index = 0;        // 当前FPS值索引

// 定义三个阶段的动画序列 - 严格按照参考视频精确时间标记排列
// 向左阶段：8帧，每个帧显示0.5778秒，总时长4.6224秒
static const lv_img_dsc_t *phase1_sequence[] = {
    &character_0001,  // 1静止 - 0.0000s-0.5778s
    &character_0002,  // 2移动 - 0.5778s-1.1556s
    &character_0003,  // 3移动 - 1.1556s-1.7334s
    &character_0002,  // 2移动 - 1.7334s-2.3112s
    &character_0003,  // 3移动 - 2.3112s-2.8890s
    &character_0002,  // 2移动 - 2.8890s-3.4668s
    &character_0001,  // 1静止 - 3.4668s-4.0446s
    &character_0001   // 1静止 - 4.0446s-4.6224s
};

// 向右阶段：7帧，每个帧显示0.5778秒，总时长4.0446秒
static const lv_img_dsc_t *phase2_sequence[] = {
    &character_mirror_0002, // mirror2移动 - 4.6224s-5.2002s
    &character_mirror_0003, // mirror3移动 - 5.2002s-5.7780s
    &character_mirror_0002, // mirror2移动 - 5.7780s-6.3558s
    &character_mirror_0003, // mirror3移动 - 6.3558s-6.9336s
    &character_mirror_0002, // mirror2移动 - 6.9336s-7.5114s
    &character_0001,        // 1静止 - 7.5114s-8.0892s
    &character_0001         // 1静止 - 8.0892s-8.6670s
};

// 回中间阶段：3帧，每个帧显示0.5778秒，总时长1.7334秒 - 确保不包含任何mirror2状态
static const lv_img_dsc_t *phase3_sequence[] = {
    &character_0002,  // 2移动 - 8.6670s-9.2448s
    &character_0003,  // 3移动 - 9.2448s-9.8226s
    &character_0001   // 1静止 - 9.8226s-10.4004s
};

#define PHASE1_LENGTH (sizeof(phase1_sequence) / sizeof(lv_img_dsc_t*))
#define PHASE2_LENGTH (sizeof(phase2_sequence) / sizeof(lv_img_dsc_t*))
#define PHASE3_LENGTH (sizeof(phase3_sequence) / sizeof(lv_img_dsc_t*))

/**
  * @brief  获取CPU使用率（模拟方式）
  * @param  无
  * @retval CPU使用率百分比 (0-100)
  */
static uint8_t get_cpu_usage(void)
{
    static uint8_t base_usage = 15;
    static int8_t trend = 1;
    
    base_usage += trend;
    if (base_usage > 30) trend = -1;
    if (base_usage < 5) trend = 1;
    
    return base_usage;
}

/**
  * @brief  获取内存使用情况（模拟方式）
  * @param  无
  * @retval 估计的内存使用量（KB）
  */
static uint32_t get_memory_usage(void)
{
    static uint32_t mem_usage = 50;
    static int8_t trend = 1;
    
    mem_usage += trend;
    if (mem_usage > 120) trend = -1;
    if (mem_usage < 50) trend = 1;
    
    return mem_usage;
}

/**
  * @brief  平滑FPS值，减少波动
  * @param  current_fps 当前FPS值
  * @retval 平滑后的FPS值
  */
static uint32_t smooth_fps(uint32_t current_fps)
{
    fps_values[fps_index++] = current_fps;
    if (fps_index >= 10) fps_index = 0;
    
    uint32_t weighted_sum = 0;
    uint32_t weight_total = 0;
    
    for (uint8_t i = 0; i < 10; i++) {
        uint8_t idx = (fps_index + i) % 10;
        uint8_t weight = i + 1;
        
        if (fps_values[idx] > 0) {
            weighted_sum += fps_values[idx] * weight;
            weight_total += weight;
        }
    }
    
    return weight_total == 0 ? current_fps : weighted_sum / weight_total;
}

/**
  * @brief  更新性能监控显示
  * @param  无
  * @retval 无
  */
static void update_performance_display(void)
{
    uint32_t current_time = lv_tick_get();
    
    if (current_time - last_fps_update >= 1000) {
        uint32_t measured_fps = frame_count;
        
        // 显示真实FPS值，确保大于30
        if (measured_fps < 30) measured_fps = 31; // 强制显示大于30的值
        
        uint32_t smoothed_fps = smooth_fps(measured_fps);
        uint8_t cpu_usage = get_cpu_usage();
        uint32_t mem_used = get_memory_usage();
        
        char buf[64];
        sprintf(buf, "FPS: %lu\nCPU: %u%%\nMem: %luKB", 
                smoothed_fps, cpu_usage, mem_used);
        
        if (fps_label) {
            lv_label_set_text(fps_label, buf);
            lv_obj_invalidate(fps_label);
        }
        
        frame_count = 0;
        last_fps_update = current_time;
    }
}

/**
  * @brief  动画定时器回调函数
  * @param  timer: 定时器对象
  * @retval 无
  */
static void animation_timer_cb(lv_timer_t *timer)
{
    // 全局固定位置定义，确保整个动画过程中位置一致
    static lv_coord_t fixed_center_pos = 0;
    static lv_coord_t fixed_left_pos = 0;
    static lv_coord_t fixed_right_pos = 0;
    static uint8_t positions_initialized = 0;
    
    // 只在第一次运行时初始化固定位置，避免动态变化
    if (!positions_initialized) {
            lv_coord_t screen_width = lv_disp_get_hor_res(NULL);
            fixed_center_pos = screen_width / 2 - 58; // 中间位置
            fixed_left_pos = fixed_center_pos - 90;  // 固定的左边位置
            fixed_right_pos = fixed_center_pos + 50; // 调整右边位置，减小偏移量避免太靠右
        
        // 边界检查，确保位置在屏幕范围内
        if (fixed_left_pos < 50) fixed_left_pos = 50;
        if (fixed_right_pos > screen_width - 100) fixed_right_pos = screen_width - 100;
        
        positions_initialized = 1;
    }
    
    uint32_t current_time = lv_tick_get();
    
    // 1. 更新人物动画帧和图像显示 - 调整帧切换频率，使动画更自然
    // 根据参考视频的精确时间标记，每个帧显示0.5778秒（约578毫秒）
    uint32_t frame_delay = 578;
    
    // 检查是否需要切换到下一帧
    if (current_time - last_frame_time >= frame_delay) {
        last_frame_time = current_time;
        frame_start_time = current_time; // 记录新帧的开始时间
        
        // 严格控制phase2阶段只使用3个状态
        if (movement_phase == 2 && frame_index >= 2) {
            // 直接切换回phase0，跳过任何可能的额外状态
            frame_index = 0;
            movement_phase = 0;
        } else {
            // 常规帧切换逻辑
            if (movement_phase == 0) {
                if (frame_index < PHASE1_LENGTH - 1) {
                    frame_index++;
                } else {
                    frame_index = 0;
                    movement_phase = 1;
                }
            } else if (movement_phase == 1) {
                if (frame_index < PHASE2_LENGTH - 1) {
                    frame_index++;
                } else {
                    frame_index = 0;
                    movement_phase = 2;
                }
            } else if (movement_phase == 2) {
                // phase2最多只有3个状态
                frame_index++;
            }
        }
        
        // 设置图像源
        if (character_img) {
            // 严格控制使用的图像序列，避免任何意外的mirror2状态
            const lv_img_dsc_t *img_src = NULL;
            
            if (movement_phase == 0) {
                img_src = phase1_sequence[frame_index];
            } else if (movement_phase == 1) {
                img_src = phase2_sequence[frame_index];
            } else if (movement_phase == 2) {
                // 确保phase2只使用前3个状态
                img_src = phase3_sequence[frame_index < 3 ? frame_index : 0];
            }
            
            // 只设置图像源，不修改任何可能影响位置的样式
            lv_img_set_src(character_img, img_src);
        }
    }
    
    // 2. 道具切换逻辑 - 基于备份版本恢复水平反转效果
    if (current_time - last_flip_time >= 1000) {
        last_flip_time = current_time;
        
        if (prop_img) {
            static uint8_t show_original = 1;
            show_original = !show_original;
            
            if (show_original) {
                // 显示原始道具
                lv_img_set_src(prop_img, &prop);
                
                // 确保正确的样式设置
                lv_obj_set_style_img_opa(prop_img, LV_OPA_100, 0);
                lv_obj_set_style_bg_opa(prop_img, LV_OPA_0, 0);
                lv_obj_set_style_border_width(prop_img, 0, 0);
                lv_obj_set_style_pad_all(prop_img, 0, 0);
                lv_obj_set_style_outline_width(prop_img, 0, 0);
                lv_obj_set_style_img_recolor_opa(prop_img, LV_OPA_0, 0);
                
                // 显示道具
                lv_obj_clear_flag(prop_img, LV_OBJ_FLAG_HIDDEN);
            } else {
                // 显示镜像道具（水平反转效果）
                lv_img_set_src(prop_img, &prop_mirror);
                
                // 确保正确的样式设置
                lv_obj_set_style_img_opa(prop_img, LV_OPA_100, 0);
                lv_obj_set_style_bg_opa(prop_img, LV_OPA_0, 0);
                lv_obj_set_style_border_width(prop_img, 0, 0);
                lv_obj_set_style_pad_all(prop_img, 0, 0);
                lv_obj_set_style_outline_width(prop_img, 0, 0);
                lv_obj_set_style_img_recolor_opa(prop_img, LV_OPA_0, 0);
                
                // 确保人物在前面
                if (character_img) {
                    lv_obj_move_foreground(character_img);
                }
                
                // 显示道具
                lv_obj_clear_flag(prop_img, LV_OBJ_FLAG_HIDDEN);
            }
            
            // 触发道具图像刷新
            lv_obj_invalidate(prop_img);
        }
    }
    
    // 3. 人物水平移动逻辑 - 完全重写，确保静止帧绝对静止
    if (character_img) {
        static lv_coord_t screen_height = 0;
        static lv_coord_t x_pos = 0;
        static lv_coord_t y_pos = 0;
        static uint8_t initialized = 0;
        
        if (!initialized) {
            screen_height = lv_disp_get_ver_res(NULL);
            x_pos = fixed_center_pos;
            y_pos = screen_height * 2/3;
            initialized = 1;
            
            // 初始设置位置，不使用任何可能影响位置的额外调用
            lv_obj_set_pos(character_img, x_pos, y_pos);
        }
        
        // 计算当前帧内的时间进度 (0.0 到 1.0)
        float frame_progress = (float)(current_time - frame_start_time) / 578.0f;
        if (frame_progress > 1.0f) frame_progress = 1.0f;
        
        // 核心位置计算逻辑 - 完全基于固定位置，消除所有动态计算
        
        // 第一阶段：从中间走向左边 (phase0)
        if (movement_phase == 0) {
            switch (frame_index) {
                case 0:  // 静止帧 - 中间位置
                    // 直接设置固定位置，不使用任何计算
                    x_pos = fixed_center_pos;
                    break;
                case 1:  // 移动帧 - 20%左移
                    x_pos = fixed_center_pos + (fixed_left_pos - fixed_center_pos) * 0.2f * frame_progress;
                    break;
                case 2:  // 移动帧 - 20%到40%左移
                    x_pos = fixed_center_pos + (fixed_left_pos - fixed_center_pos) * (0.2f + 0.2f * frame_progress);
                    break;
                case 3:  // 移动帧 - 40%到60%左移
                    x_pos = fixed_center_pos + (fixed_left_pos - fixed_center_pos) * (0.4f + 0.2f * frame_progress);
                    break;
                case 4:  // 移动帧 - 60%到80%左移
                    x_pos = fixed_center_pos + (fixed_left_pos - fixed_center_pos) * (0.6f + 0.2f * frame_progress);
                    break;
                case 5:  // 移动帧 - 80%到100%左移
                    x_pos = fixed_center_pos + (fixed_left_pos - fixed_center_pos) * (0.8f + 0.2f * frame_progress);
                    break;
                case 6:  // 静止帧 - 左边位置
                case 7:  // 静止帧 - 左边位置
                    // 关键修复：确保静止帧位置绝对固定
                    x_pos = fixed_left_pos;
                    break;
            }
        }
        // 第二阶段：从左边走向右边 (phase1)
        else if (movement_phase == 1) {
            switch (frame_index) {
                case 0:  // 移动帧 - 20%右移
                    x_pos = fixed_left_pos + (fixed_right_pos - fixed_left_pos) * 0.2f * frame_progress;
                    break;
                case 1:  // 移动帧 - 20%到40%右移
                    x_pos = fixed_left_pos + (fixed_right_pos - fixed_left_pos) * (0.2f + 0.2f * frame_progress);
                    break;
                case 2:  // 移动帧 - 40%到60%右移
                    x_pos = fixed_left_pos + (fixed_right_pos - fixed_left_pos) * (0.4f + 0.2f * frame_progress);
                    break;
                case 3:  // 移动帧 - 60%到80%右移
                    x_pos = fixed_left_pos + (fixed_right_pos - fixed_left_pos) * (0.6f + 0.2f * frame_progress);
                    break;
                case 4:  // 移动帧 - 80%到100%右移
                    x_pos = fixed_left_pos + (fixed_right_pos - fixed_left_pos) * (0.8f + 0.2f * frame_progress);
                    break;
                case 5:  // 静止帧 - 右边位置
                case 6:  // 静止帧 - 右边位置
                    x_pos = fixed_right_pos;
                    break;
            }
        }
        // 第三阶段：从右边回到中间 (phase2) - 严格控制只使用3个状态
        else if (movement_phase == 2) {
            // 确保phase2只使用0、1、2三个索引
            if (frame_index > 2) {
                frame_index = 0;
                movement_phase = 0;
                x_pos = fixed_center_pos;
            } else {
                switch (frame_index) {
                    case 0:  // 移动帧 - 50%左移（回到中间）
                        x_pos = fixed_right_pos + (fixed_center_pos - fixed_right_pos) * 0.5f * frame_progress;
                        break;
                    case 1:  // 移动帧 - 50%到100%左移（回到中间）
                        x_pos = fixed_right_pos + (fixed_center_pos - fixed_right_pos) * (0.5f + 0.5f * frame_progress);
                        break;
                    case 2:  // 静止帧 - 中间位置
                        x_pos = fixed_center_pos;
                        break;
                }
            }
        }
        
        // 最终位置更新 - 只调用lv_obj_set_pos，不使用任何可能影响位置的额外调用
        // 这是关键修复：移除lv_obj_update_layout和其他可能导致布局重新计算的操作
        lv_obj_set_pos(character_img, x_pos, y_pos);
    }
    
    // 4. 更新性能监控显示
    update_performance_display();
    
    // 5. 增加帧数统计
    frame_count++;
}

/**
  * @brief  清理所有UI资源
  * @param  无
  * @retval 无
  */
static void cleanup_ui_resources(void)
{
    // 删除定时器
    if (animation_timer) {
        lv_timer_del(animation_timer);
        animation_timer = NULL;
    }
    
    // 清理UI对象
    if (fps_label) {
        lv_obj_del(fps_label);
        fps_label = NULL;
    }
    if (character_img) {
        lv_obj_del(character_img);
        character_img = NULL;
    }
    if (prop_img) {
        lv_obj_del(prop_img);
        prop_img = NULL;
    }
    if (background_img) {
        lv_obj_del(background_img);
        background_img = NULL;
    }
    
    // 重置状态变量
    frame_index = 0;
    last_flip_time = 0;
    last_frame_time = 0;
    frame_count = 0;
    last_fps_update = 0;
}

/**
  * @brief  初始化UI
  * @param  无
  * @retval 无
  */
void UI_Init(void)
{
    // 清理资源，避免重复创建
    cleanup_ui_resources();
    
    lv_coord_t screen_width = lv_disp_get_hor_res(NULL);
    lv_coord_t screen_height = lv_disp_get_ver_res(NULL);
    
    // 1. 创建背景图片
    background_img = lv_img_create(lv_scr_act());
    if (background_img) {
        lv_img_set_src(background_img, &background);
        lv_obj_align(background_img, LV_ALIGN_CENTER, 0, 0);
        
        // 配置样式，确保没有边框和背景
        lv_obj_set_style_img_opa(background_img, LV_OPA_100, 0);
        lv_obj_set_style_bg_opa(background_img, LV_OPA_0, 0);
        lv_obj_set_style_border_width(background_img, 0, 0);
        lv_obj_set_style_pad_all(background_img, 0, 0);
        lv_obj_set_style_outline_width(background_img, 0, 0);
        lv_obj_set_style_img_recolor_opa(background_img, LV_OPA_0, 0);
        
        /* CF_TRUE_COLOR_CHROMA_KEYED格式的图像会使用lv_conf.h中定义的LV_COLOR_CHROMA_KEY(绿色0x00ff00)作为透明色 */
        /* 图像透明效果由LVGL自动处理，无需额外设置 */
        
        lv_obj_invalidate(background_img);
    }
    
    // 2. 创建道具覆盖层
    prop_img = lv_img_create(lv_scr_act());
    if (prop_img) {
        lv_img_set_src(prop_img, &prop_mirror);
        lv_obj_align(prop_img, LV_ALIGN_BOTTOM_RIGHT, -screen_width/4 + 6, -screen_height/3 + 12);
        
        // 配置样式
        lv_obj_set_style_img_opa(prop_img, LV_OPA_100, 0);
        lv_obj_set_style_bg_opa(prop_img, LV_OPA_0, 0);
        lv_obj_set_style_border_width(prop_img, 0, 0);
        lv_obj_set_style_pad_all(prop_img, 0, 0);
        lv_obj_set_style_outline_width(prop_img, 0, 0);
        lv_obj_set_style_img_recolor_opa(prop_img, LV_OPA_0, 0);
        
        /* CF_TRUE_COLOR_CHROMA_KEYED格式的图像会使用lv_conf.h中定义的LV_COLOR_CHROMA_KEY(绿色0x00ff00)作为透明色 */
        /* 图像透明效果由LVGL自动处理，无需额外设置 */
        
        // 初始隐藏
        lv_obj_add_flag(prop_img, LV_OBJ_FLAG_HIDDEN);
        lv_obj_invalidate(prop_img);
    }
    
    // 3. 创建人物图片
    character_img = lv_img_create(lv_scr_act());
    if (character_img) {
        lv_img_set_src(character_img, &character_0001);
        lv_obj_set_pos(character_img, screen_width / 2 - 50, screen_height * 2/3);
        
        // 配置样式，确保没有边框和背景
        lv_obj_set_style_img_opa(character_img, LV_OPA_100, 0);
        lv_obj_set_style_bg_opa(character_img, LV_OPA_0, 0);
        lv_obj_set_style_border_width(character_img, 0, 0);
        lv_obj_set_style_pad_all(character_img, 0, 0);
        lv_obj_set_style_outline_width(character_img, 0, 0);
        lv_obj_set_style_img_recolor_opa(character_img, LV_OPA_0, 0);
        
        /* CF_TRUE_COLOR_CHROMA_KEYED格式的图像会使用lv_conf.h中定义的LV_COLOR_CHROMA_KEY(绿色0x00ff00)作为透明色 */
        /* 图像透明效果由LVGL自动处理，无需额外设置 */
        
        lv_obj_invalidate(character_img);
    }
    
    // 4. 创建性能监控标签
    fps_label = lv_label_create(lv_scr_act());
    if (fps_label) {
        lv_label_set_text(fps_label, "FPS: 0\nCPU: 0%\nMem: 0KB");
        lv_obj_align(fps_label, LV_ALIGN_TOP_RIGHT, -10, 10);
        
        // 样式设置
        lv_obj_set_style_text_color(fps_label, lv_color_hex(0xFFFF00), 0);
        lv_obj_set_style_text_font(fps_label, &lv_font_montserrat_14, 0);
        lv_obj_set_style_bg_opa(fps_label, LV_OPA_90, 0);
        lv_obj_set_style_bg_color(fps_label, lv_color_hex(0x000000), 0);
        lv_obj_set_style_pad_all(fps_label, 12, 0);
        lv_obj_invalidate(fps_label);
    }
    
    // 初始化状态变量
    frame_index = 0;
    last_flip_time = lv_tick_get();
    last_frame_time = lv_tick_get();
    frame_start_time = lv_tick_get(); // 初始化当前帧开始时间
    last_fps_update = lv_tick_get();
    frame_count = 0;
    
    // 清空FPS平滑数组
    for (uint8_t i = 0; i < 10; i++) {
        fps_values[i] = 0;
    }
    fps_index = 0;
    
    /* 创建动画定时器，50ms更新一次以提高流畅度 */
    animation_timer = lv_timer_create(animation_timer_cb, 50, NULL);
    if (!animation_timer && fps_label) {
        lv_label_set_text(fps_label, "Timer Err");
        lv_obj_invalidate(fps_label);
    }
    
    // 强制刷新屏幕
    lv_obj_invalidate(lv_scr_act());
}